package hn.cch.indicator;

import java.util.List;

public class Beta implements Indicator {

    public Double indicator(List<Return> R) {

        int T = R.size();

        Double sumPortfolio = R.stream().mapToDouble(Return::getRp).sum();
        Double sumBenchmark = R.stream().mapToDouble(Return::getRp).sum();

        R.forEach(p -> p.setRt(p.getRb() * p.getRp()));
        Double sumBenchmarkPortfolio = R.stream().mapToDouble(Return::getRt).sum();

        R.forEach(p -> p.setRt(Math.pow(p.getRb(), 2)));
        Double sumBenchmarkSquare = R.stream().mapToDouble(Return::getRt).sum();

        Double beta = (sumBenchmarkPortfolio - sumBenchmark * sumPortfolio / T)
                / (sumBenchmarkSquare - Math.pow(sumPortfolio, 2) / T);
        return beta;
    }
}
